package com.sherlockHolmes.init.auth2;

import com.sherlockHolmes.init.base.utils.JWTUtil;
import com.sherlockHolmes.init.entity.dao.Permissioins;
import com.sherlockHolmes.init.entity.dao.UserInfo;
import com.sherlockHolmes.init.service.PermissioinsService;
import com.sherlockHolmes.init.service.UserInfoService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserInfoService userService;
    @Autowired
    private PermissioinsService permissionsService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = JWTUtil.getUsername(principals.toString());
        UserInfo member = userService.getUserByName(username);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
       // 查询权限信息
        List<Permissioins> permissions = permissionsService.getPermissions( member);
        List list=new ArrayList<>();
        for (Permissioins per: permissions
             ) {
            String permCode = per.getPermCode();
            list.add(permCode);
        }
        info.addStringPermissions(list);
        return info;
    }

    /**
     * 使用JWT替代原生Token
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        String token = (String) authcToken.getCredentials();

        String username = JWTUtil.getUsername(token);

        UserInfo member = userService.getUserByName(username);

        // 用户不会空
        if (member != null) {
            // 判断是否禁用
            if (member.getUsable()==1) {
                throw new DisabledAccountException("账号已被封禁");
            }

            // 密码验证
            if (!JWTUtil.verify(token, username, member.getPassword())) {
                throw new UnknownAccountException("密码错误");
            }

            return new SimpleAuthenticationInfo(token, token, "realm");
        } else {
            throw new UnknownAccountException("未登录");
        }
    }
}
